package com.ocm.tourism.core.dao.jpa;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.ocm.tourism.core.dao.TranslationDao;
import com.ocm.tourism.core.domain.Catalogues;
import com.ocm.tourism.core.domain.ContentTranslate;
import com.ocm.tourism.core.domain.LanguageType;
import com.ocm.tourism.core.domain.TransalationType;

@Repository("translationDao")
public class JpaTranslationDao extends JpaGenericDao<ContentTranslate> implements TranslationDao {

   public JpaTranslationDao() {
      this.setClazz(ContentTranslate.class);
   }

   @Override
   public void saveCatalogues(Catalogues catalogues) {
      ContentTranslate contentTranslate = find(catalogues.getId(), TransalationType.Catalogue, LanguageType.current());
      if (contentTranslate == null){
         contentTranslate = new ContentTranslate();
      }
      contentTranslate.setContent(catalogues.getContent());
      contentTranslate.setDescription(catalogues.getDescription());
      contentTranslate.setName(catalogues.getName());
      contentTranslate.setForeignKey(catalogues.getId());
      contentTranslate.setTransalationType(TransalationType.Catalogue);
      contentTranslate.setLanguageType(LanguageType.current());
      if (contentTranslate.getId() == null || contentTranslate.getId() == 0){
         this.entityManager().persist(contentTranslate);
      }else {
         this.entityManager().merge(contentTranslate);
      }
   }

   @Override
   public Catalogues find(Catalogues catalogues) {
      ContentTranslate contentTranslate = find(catalogues.getId(), TransalationType.Catalogue, LanguageType.current());
      if (contentTranslate != null){
         catalogues.setName(contentTranslate.getName());
         catalogues.setDescription(contentTranslate.getDescription());
         catalogues.setContent(contentTranslate.getContent());;
      }
      return catalogues;
   }

   @SuppressWarnings("unchecked")
   public ContentTranslate find(long foreginKey, TransalationType transalationType, LanguageType languageType) {
      Query query = this.entityManager().createQuery("SELECT c FROM ContentTranslate c WHERE c.foreignKey=:foreignKey AND c.transalationType=:transalationType AND c.languageType=:languageType", ContentTranslate.class);
      query.setParameter("foreignKey", foreginKey);
      query.setParameter("transalationType", transalationType);
      query.setParameter("languageType", languageType);
      List<ContentTranslate> contentTranslates = query.getResultList();
      ContentTranslate contentTranslate = null;
      if (contentTranslates.size() > 0){
         contentTranslate = contentTranslates.get(0);
      }
      return contentTranslate;
   }
}
